package com.cybertooth.dbconvenience.query.core;

import com.cybertooth.dbconvenience.query.columns.OrderByColumn;
import com.cybertooth.dbconvenience.query.functions.SqlTransformerFunction;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;

import java.util.Deque;

/**
 * <p></p>
 *
 * @author dnelson
 */
public class OrderBy implements SqlTransformer {

	// -----------------------------------------------------------------------Fields

	protected Deque<OrderByColumn> columns;

	// -----------------------------------------------------------------Constructors

	public static OrderBy orderBy(OrderByColumn orderByColumn) {
		return new OrderBy(orderByColumn);
	}

	private OrderBy(OrderByColumn orderByColumn) {
		this.columns = Lists.newLinkedList();
		this.columns.push(orderByColumn);
	}

	// ---------------------------------------------------------------Public Methods

	public OrderBy and(OrderByColumn orderByColumn) {
		this.columns.push(orderByColumn);
		return this;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public String toSql() {
		return new StringBuilder()
				.append(" ORDER BY ")
				.append(Joiner.on(",").join(Iterables.transform(this.columns, new SqlTransformerFunction())))
				.toString();
	}
}
